package util;

import datastructure.TreeNode;
import datastructure.intdata.TreeLinkNode;

public class TreeConstructor {
	public static TreeNode getTree(int[] data) {
		return constructTree(data, 0);
	}
	
	static TreeNode constructTree(int[] data, int idx) {
		TreeNode node = null;
		if(idx < data.length) {
			node = new TreeNode(data[idx]);
			node.left = constructTree(data, 2*idx + 1);
			node.right = constructTree(data, 2*idx + 2);
		}
		return node;
	}
	
	public static TreeLinkNode getLinkTree(int[] data) {
		return constructLinkTree(data, 0);
	}
	
	static TreeLinkNode constructLinkTree(int[] data, int idx) {
		TreeLinkNode node = null;
		if(idx < data.length) {
			node = new TreeLinkNode(data[idx]);
			node.left = constructLinkTree(data, 2*idx + 1);
			node.right = constructLinkTree(data, 2*idx + 2);
			if(node.left != null) node.left.next = node;
			if(node.right != null) node.right.next = node;
		}
		return node;
	}
	
	public static void showTreePre(TreeNode tree) {
		if(tree != null) {
			System.out.print(tree.data + " ");
			showTreePre(tree.left);
			showTreePre(tree.right);
		}
	}
}
